package com.unionwo.controller;


import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import it.sauronsoftware.base64.Base64;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.unionwo.commons.exception.DaoException;
import com.unionwo.commons.util.HttpUtils;
import com.unionwo.dto.ComplainInfoReq;
import com.unionwo.json.BaiduLocationInfoJson;
import com.unionwo.model.ComplainLog;
import com.unionwo.service.ComplainLogService;

@Controller
@RequestMapping("/complain")
public class ComplainLogController {
	private Logger log = Logger.getLogger(ComplainLogController.class);
	@Autowired
	private ComplainLogService complainLogService;
	
	
	static Map<Integer,String> semaphoreDictMap = new HashMap<Integer,String>();
	static Map<Integer,String> module2ClassMap = new HashMap<Integer,String>();
	static {
		semaphoreDictMap.put(1, "非常好");
		semaphoreDictMap.put(2, "较好");
		semaphoreDictMap.put(3, "一般");
		semaphoreDictMap.put(4, "较差");
		semaphoreDictMap.put(5, "非常差");
		semaphoreDictMap.put(6, "无信号");
		
		module2ClassMap.put(10, "");
	}
	
	/***
	 * 
	 * @param request 
	 * @param userToken 第一版先随便传值
	 * @param telephoneNumber 电话号码
	 * @param semaphore       信号强弱数字表示
	 * @param longitude       经度 
	 * @param latitude        纬度
	 * @param province        省 
	 * @param city            城市
	 * @param area            区/县
	 * @param address         详细地址
	 * @param time            投诉事件
	 * @return
	 */
	@RequestMapping("/postComplain")
	@ResponseBody
	public int postComplainInfo(HttpServletRequest request,@RequestParam(value="u",required=false) String userToken,
			@RequestParam(value="n")String telephoneNumber,@RequestParam(value="s")String semaphore,
			@RequestParam(value="lg")String longitude,@RequestParam(value="lt")String latitude,@RequestParam(value="p")String province,
			@RequestParam(value="c")String city,@RequestParam(value="a")String area,@RequestParam(value="r")String address,@RequestParam(value="t")String time){
		String semaphoreFlag = semaphoreDictMap.get(Integer.parseInt(semaphore));
		ComplainInfoReq c = new ComplainInfoReq(userToken, telephoneNumber,Double.parseDouble(semaphore),  semaphoreFlag,  Double.parseDouble(longitude),
				Double.parseDouble(latitude), province,  city,  area,address,time) ;
		//decodeComplianLog(c);
//		ComplainLog cLog = null;
//		cLog = complainLogService.revert2ComplainLogFromDto(c);
//		String key = longitude+"*"+latitude;
//		Long l = countMap.get(key);
//		if(null==l){
//			countMap.put(key, 1l);
//		}else{
//			countMap.put(key, ++l);
//		}
//		try {
//			complainLogService.insertComplainLog(cLog);
//		} catch (DaoException e) {
//			log.error("record "+userToken+" insert failure."+e);
//		}
		return 1;
	}
	
	
	/****
	 * 
	 * @param longitude  经度
	 * @param latitude
	 * @return String 注意 中文以unicode编码 解析json的时候转换一下
	 * @throws Exception 
	 */
	@RequestMapping(value="/convert2Address",method=RequestMethod.GET)
	@ResponseBody
	public static String convert2Address(@RequestParam(value="lg",required=false)double longitude ,@RequestParam(value="lt",required=false)double latitude) throws Exception{
		System.out.println("ready");
		String url = "http://lbs.juhe.cn/api/getaddressbylngb?lngx="+longitude+"&lngy="+latitude;
		return HttpUtils.executeGet(url);
	}
	
	public void decodeComplianLog(ComplainInfoReq c){
		c.setAddress(Base64.decode(c.getAddress()));
		c.setArea(Base64.decode(c.getArea()));
		c.setCity(Base64.decode(c.getCity()));
		c.setLatitude(Double.parseDouble(Base64.decode(String.valueOf(c.getLatitude()))));
		c.setLongitude(Double.parseDouble(Base64.decode(String.valueOf(c.getLongitude()))));
		c.setProvince(Base64.decode(c.getProvince()));
		c.setSemaphore(Double.parseDouble(Base64.decode(String.valueOf(c.getSemaphore()))));
		c.setSemaphoreFlag(Base64.decode(c.getSemaphoreFlag()));
		c.setTelephoneNumber(Base64.decode(c.getTelephoneNumber()));
		c.setUserToken(Base64.decode(c.getUserToken()));
	}
	
	private static final boolean ISDECODE=false;
	
	@RequestMapping(value="/service",method=RequestMethod.GET)
	@ResponseBody
	public String doService(HttpServletRequest request){
		String semaphoreFlag = semaphoreDictMap.get(Integer.parseInt(request.getParameter("s")));
		request.setAttribute("semaphoreFlag", Base64.decode(semaphoreFlag));
		Map<String,String> map = parseBaseParameter(request);
		String userToken = map.get("userToken");
		String phoneNumber = map.get("phoneNumber");
		//1.Base64 decode
		//2.check userToken
		//是否需要统计流量
		//3.bussiness 
		
		//4.response
		return null;
	}
	/****
	 * only parse parameter  userToken phoneNumber
	 * if ISDECODE is true ,Base64 encoder is valid ,or invalid
	 * default is false ,use test.
	 * @param request
	 * @return Map
	 */
	static Map<String,String> parseBaseParameter(HttpServletRequest request){
		Map<String,String> map = new HashMap<String,String>();
		String userToken = request.getParameter("u");
		String phoneNumber = request.getParameter("n");
		if(ISDECODE){
			map.put("userToken", userToken);
			map.put("phoneNumber", phoneNumber);
		}else{
			map.put("userToken", Base64.decode(userToken));
			map.put("phoneNumber", Base64.decode(phoneNumber));
		}
		return map;
	}
	
	public static void main(String args[]){
		Random r = new Random();
		DecimalFormat df=new DecimalFormat("#.##");
		
		for(int i=0;i<100;i++){
			System.out.println(df.format(r.nextDouble()));
		}

		
//		BaiduLocationInfoJson j = new BaiduLocationInfoJson();
//		JSONObject jo = JSONObject.fromObject(j);
//		System.out.println(jo);
		/****
		double a= 119.9772857,b=27.327578;
		try {
			String abc = convert2Address(a,b);
			//String ns=new String(abc.getBytes("utf-8"),"gbk");
			JSONObject jsonObject = JSONObject.fromObject(abc);
			BaiduLocationInfoJson bc = (BaiduLocationInfoJson)JSONObject.toBean(jsonObject, BaiduLocationInfoJson.class);
			System.out.println(bc.getResultcode());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		***/
	}
	
}
